package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.controller.ESController;
import cn.xuewenbao.edu.entity.*;
import cn.xuewenbao.edu.entity.vo.ArticleInfoVo;
import cn.xuewenbao.edu.entity.vo.ArticlePublishVo;
import cn.xuewenbao.edu.entity.vo.DraftVo;
import cn.xuewenbao.edu.entity.vo.GoodVo;
import cn.xuewenbao.edu.mapper.ArticleMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.entity.vo.MemberProfileVo;
import cn.xuewenbao.ucenter.service.FollowService;
import cn.xuewenbao.ucenter.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-03-22
 */
@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    private final String ColumnTypeArticle = "1";

    @Autowired
    private MemberService memberService;

    @Autowired
    private ColumnDataService columnDataService;

    @Autowired
    private LikeContentService likeContentService;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private ViewContentService viewContentService;

    @Autowired
    private ContentSubjectService contentSubjectService;

    @Autowired
    private ESController esController;

    @Autowired
    private GoodLinkService linkService;

    //根据文章id查询文章基本信息
    @Override
    public ArticleInfoVo getArticleInfo(String articleId, String userId) {
        ArticleInfoVo vo = new ArticleInfoVo();
        //获取 vo中 article的基本信息
        Article article = baseMapper.selectById(articleId);
        //阅读数加1
        article.setViewCount(article.getViewCount() + 1);
        baseMapper.updateById(article);

        //将阅读记录添加到阅读表中
        ViewContent viewContent = new ViewContent();
        viewContent.setContentId(articleId);
        viewContent.setColumnType(ColumnTypeArticle);
        viewContent.setAuthorId(article.getUserId());
        viewContent.setUserId(userId);
        viewContentService.save(viewContent);

        BeanUtils.copyProperties(article, vo);
        //获取 vo中 作者的昵称, 头像, 用户是否关注
        Result<MemberProfileVo> memberProfileVoResult = memberService.getMemberProfile(article.getUserId(), userId);
        MemberProfileVo memberProfileVo = memberProfileVoResult.getResult();
        vo.setUserName(memberProfileVo.getUsername());
        vo.setAvatar(memberProfileVo.getAvatar());
        vo.setIsFollow(memberProfileVo.getIsFollow());
        //获取 vo中 用户是否点赞, 收藏
        vo.setIsLike(likeContentService.hasLikeOne(userId, articleId, ColumnTypeArticle).isSuccess());
        vo.setIsFavorite(favoriteService.hasFavoriteOne(userId, articleId, ColumnTypeArticle).isSuccess());
        //获取 vo中 文章的点赞数, 收藏数
        ColumnData columnData = columnDataService.getOne(new QueryWrapper<ColumnData>().eq("content_id", articleId).eq("column_type", ColumnTypeArticle));
        if (columnData != null) {
            //专栏数据表同步阅读数
            columnData.setViewCount(article.getViewCount());
            columnDataService.updateById(columnData);
            vo.setLikeCount(columnData.getLikeCount());
            vo.setFavoriteCount(columnData.getFavoriteCount());
        }
        return vo;
    }

    //根据id排序获取文章用于首页显示
    @Override
    public List<ArticleInfoVo> getIndexArticleInfoVo() {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.eq("status","Approval");
        wrapper.last("limit 2");
        List<Article> articleList = baseMapper.selectList(wrapper);
        List<ArticleInfoVo> articleInfoVoList = new ArrayList<>();
        for (int i = 0; i < articleList.size(); i++) {
            ArticleInfoVo articleInfoVo = new ArticleInfoVo();
            BeanUtils.copyProperties(articleList.get(i), articleInfoVo);
            articleInfoVoList.add(articleInfoVo);
        }
        return articleInfoVoList;
    }

    //根据访问量排序获取文章-用于轮播图
    @Override
    public List<ArticleInfoVo> getHotArticle() {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("view_count");
        wrapper.eq("status","Approval");
        wrapper.last("limit 2");
        List<Article> articleList = baseMapper.selectList(wrapper);
        List<ArticleInfoVo> articleInfoVoList = new ArrayList<>();
        for (int i = 0; i < articleList.size(); i++) {
            ArticleInfoVo articleInfoVo = new ArticleInfoVo();
            BeanUtils.copyProperties(articleList.get(i), articleInfoVo);
            articleInfoVoList.add(articleInfoVo);
        }
        return articleInfoVoList;
    }

    //获取所有文章
    @Override
    public List<ArticleInfoVo> listAllArticleInfo() {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","Approval");
        List<Article> articleList = baseMapper.selectList(queryWrapper);
        List<ArticleInfoVo> articleInfoVoList = new ArrayList<>();
        for (int i = 0; i < articleList.size(); i++) {
            ArticleInfoVo articleInfoVo = new ArticleInfoVo();
            BeanUtils.copyProperties(articleList.get(i), articleInfoVo);
            articleInfoVoList.add(articleInfoVo);
        }
        return articleInfoVoList;
    }

    //添加文章
    @Override
    public String addArticle(ArticlePublishVo articlePublishVo) {
        Article article = new Article();
        BeanUtils.copyProperties(articlePublishVo, article);
        int insert = baseMapper.insert(article);
        if (insert > 0) {
            final val id = article.getId();

            //添加好物推荐
            GoodVo goodVo = articlePublishVo.getGoodVo();
            if (goodVo == null) {
                log.info("好物链接为空");
            } else {
                GoodLink goodLink = new GoodLink();
                BeanUtils.copyProperties(goodVo, goodLink);
                goodLink.setGoodId(id);
                goodLink.setUserId(article.getUserId());
                goodLink.setType("article");
                linkService.save(goodLink);
                log.info("添加好物链接成功");
            }

            val subjectList = articlePublishVo.getSubjectList();
            for (String s : subjectList) {
                ContentSubject contentSubject = new ContentSubject();
                contentSubject.setContentId(id);
                contentSubject.setSubjectId(s);
                contentSubject.setColumnType(ColumnTypeArticle);
                contentSubjectService.save(contentSubject);
            }
            //为添加的文章, 初始化 columnData为全0
            Boolean dataSuccess = columnDataService.addColumnData(id, ColumnTypeArticle, 0L, 0L, 0L, 0L);
            if (dataSuccess) {
                return id;
            } else {
                return "添加文章数据失败";
            }
        } else {
            return "添加文章失败";
        }
    }



//    @Override
//    public void updateCascade(String id, String username) {
//        QueryWrapper<Article> wrapper=new QueryWrapper<>();
//        wrapper.eq("user_id",id);
//        List<Article> article=baseMapper.selectList(wrapper);
//        for (int i = 0; i < article.size(); i++) {
//            article.get(i).setUserName(username);
//            baseMapper.updateById(article.get(i));
//        }
//    }

    @Override
    public Result<List<ArticleInfoVo>> getArticleList(String memberId) {
        Result<List<ArticleInfoVo>> result = new Result<>();
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", memberId);
        wrapper.eq("status","Approval");
        List<Article> articleList = baseMapper.selectList(wrapper);
        List<ArticleInfoVo> articleInfoVoList = new ArrayList<>();
        for (int i = 0; i < articleList.size(); i++) {
            ArticleInfoVo articleInfoVo = new ArticleInfoVo();
            BeanUtils.copyProperties(articleList.get(i), articleInfoVo);
            articleInfoVoList.add(articleInfoVo);
        }
        result.setResult(articleInfoVoList);
        result.setSuccess(true);
        return result;
    }

    //根据id删除某篇文章或者草稿
    @Override
    public Result<?> deleteArticle(String articleId) {
        Result<?> result = new Result<>();
        int res = baseMapper.deleteById(articleId);
        if (res == 0) {
            result.setMessage("删除文章失败");
            result.setSuccess(false);
            return result;
        }
        result.setMessage("删除文章成功");
        result.setSuccess(true);
        return result;
    }

    //添加文章到草稿箱
    @Override
    public Result<Boolean> addDraft(ArticlePublishVo articlePublishVo) {
        Result<Boolean> result = new Result<>();

        Article article = new Article();
        BeanUtils.copyProperties(articlePublishVo, article);
        int insert = baseMapper.insert(article);
        if (insert == 0) {
            result.setMessage("添加到草稿箱失败");
            result.setSuccess(false);
            result.setResult(false);
            return result;
        }
        result.setMessage("添加到草稿箱成功");
        result.setSuccess(true);
        result.setResult(true);
        return result;
    }

    //获取草稿箱
    @Override
    public Result<List<DraftVo>> getDraftList(String userId) {
        Result<List<DraftVo>> result = new Result<>();
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("status", "Draft");
        List<Article> articleList = baseMapper.selectList(wrapper);
        if (articleList == null) {
            result.setMessage("草稿箱为空");
            result.setSuccess(false);
            return result;
        }
        List<DraftVo> draftVoList = new ArrayList<>();
        for (Article article : articleList) {
            DraftVo draftVo = new DraftVo();
            BeanUtils.copyProperties(article, draftVo);
            Member member = memberService.getById(userId);
            final val avatar = member.getAvatar();
            draftVo.setAvatar(avatar);
            draftVoList.add(draftVo);
        }
        result.setMessage("获取草稿箱成功");
        result.setSuccess(true);
        result.setResult(draftVoList);
        return result;
    }

    //根据id和作者id删除文章
    @Override
    public Result<?> deleteOwnArticle(String articleId, String userId) {
        Result<?> result = new Result<>();
        Article article = baseMapper.selectById(articleId);
        if (article == null) {
            result.setMessage("文章为空");
            result.setSuccess(false);
            return result;
        }
        if (!article.getUserId().equals(userId)) {
            result.setMessage("没有删除权限");
            result.setSuccess(false);
            return result;
        }
        int res = baseMapper.deleteById(articleId);
        if (res == 0) {
            result.setMessage("删除文章失败");
            result.setSuccess(false);
            return result;
        }
        result.setMessage("删除文章成功");
        result.setSuccess(true);
        return result;
    }

}
